﻿Imports System.Threading.Thread

Public Class Camera
    Declare Function SendMessage Lib "coredll.dll" (ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As IntPtr
    Declare Function GetForegroundWindow Lib "coredll.dll" () As IntPtr

    Dim objCam As Microsoft.WindowsMobile.Forms.CameraCaptureDialog

    Public Sub Init(ByVal InitialDirectory As String)
        objCam = New Microsoft.WindowsMobile.Forms.CameraCaptureDialog
        objCam.InitialDirectory = InitialDirectory
        objCam.Mode = Microsoft.WindowsMobile.Forms.CameraCaptureMode.Still
        objCam.Resolution = New System.Drawing.Size(640, 480) 'HKEY_LOCAL_MACHINE\Software\Microsoft\Pictures\Camera\OEM\PictureResolution\5
        objCam.StillQuality = Microsoft.WindowsMobile.Forms.CameraCaptureStillQuality.High
    End Sub

    Public Function Capture(ByVal FileName As String) As String
        objCam.DefaultFileName = FileName
        Dim ThTimer As New System.Threading.Thread(AddressOf fnTimer)
        ThTimer.Start()
        objCam.ShowDialog()
        Return String.Format("{0}\{1}", objCam.InitialDirectory.TrimEnd("\"), FileName)
    End Function

    Private Sub fnTimer()
        'Wait 3000 mill then perform capture and close the camera dialog
        Sleep(3000)
        Dim hWnd = GetForegroundWindow
        SendMessage(hWnd, &H201, &H0, MakeDWord(240, 750))
        Sleep(100)
        SendMessage(hWnd, &H202, &H0, MakeDWord(240, 750))
        'Close the dialog after capture
        Sleep(2000)
        SendMessage(hWnd, &H10, &H0, &H0)
    End Sub

    Private Function MakeDWord(ByVal LoWord As Integer, ByVal HiWord As Integer) As Long
        MakeDWord = (HiWord * &H10000) Or (LoWord And &HFFFF&)
    End Function

End Class
